import { isArray } from "lodash-es";

export const useTreeBuildKeys = () => {
    const buildTreeKeys = (
        data = [],
        fields = { children: "children", title: "name", key: "id" }
    ) => {
        const keys = Object.entries(fields);
        return data.map((o) => {
            keys.forEach(([k, v]) => (o[k] = o[v]));
            const children = o.children || [];
            if (isArray(children) && children.length) {
                o = {
                    ...o,
                    children: buildTreeKeys(children),
                };
            }
            return o;
        });
    };

    let dataList = [];
    const generateList = (data = []) => {
        for (let i = 0; i < data.length; i++) {
            const node = data[i];
            const key = node.key;
            dataList.push({ key, title: node.title });
            if (node.children) {
                generateList(node.children);
            }
        }
        return dataList;
    };

    const getParentKey = (key, tree) => {
        let parentKey;
        for (let i = 0; i < tree.length; i++) {
            const node = tree[i];
            if (node.children) {
                if (node.children.some((item) => item.key === key)) {
                    parentKey = node.key;
                } else if (getParentKey(key, node.children)) {
                    parentKey = getParentKey(key, node.children);
                }
            }
        }
        return parentKey;
    };

    return {
        buildTreeKeys,
        generateList,
        getParentKey,
    };
};
